package yueyong.salarymanagement.util;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import yueyong.salarymanagement.module.business.salary.domain.vo.ItemData;
import yueyong.salarymanagement.module.business.salary.domain.vo.SalaryImportData;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Copyright: yueyong (c) 2022
 *
 * @author he.shaorong
 * @version 1.0
 * @date 2022/2/4
 */
public class SendEmailUtil {

    private static final String url = "https://api.sendcloud.net/apiv2/mail/send";
    private static final String apiUser = "sc_kcw9xt_test_H9VBdw";
    private static final String apiKey = "0b45efb64099a86298290d6878032cca";
    private static final String subjectTitle = "本月薪资已发放，请查收！";

    private static final String slaryPlatform = "悦用工资条";
    private static final String platform = "悦用公司";
    private static final String ICON_URL = "https://6661-fat-4gjiv98tc2104267-1309602981.tcb.qcloud.la/%E9%82%AE%E4%BB%B6%E6%8C%87%E5%AF%BC%E5%9B%BE.png?sign=33521cea771033bfebfb9dc2f908a65c&t=1652622341";
    private static final String YUEYONG_URL = "https://gzt.yyysmart.com/";

    public static boolean sendEmail(String content, String targetEmailAddress) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httPost = new HttpPost(url);

        List params = new ArrayList();
        // 您需要登录SendCloud创建API_USER，使用API_USER和API_KEY才可以进行邮件的发送。
        params.add(new BasicNameValuePair("apiUser", apiUser));
        params.add(new BasicNameValuePair("apiKey", apiKey));
        params.add(new BasicNameValuePair("from", "service@sendcloud.im"));
        params.add(new BasicNameValuePair("fromName", ""));
        params.add(new BasicNameValuePair("to", targetEmailAddress));
        params.add(new BasicNameValuePair("subject", subjectTitle));
        params.add(new BasicNameValuePair("html", content));

        try {
            httPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            // 请求
            HttpResponse response = httpclient.execute(httPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 正常返回
                // 读取xml文档
                String result = EntityUtils.toString(response.getEntity());
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        } finally {
            httPost.releaseConnection();
        }
    }


    public static String buildHtmlContent(String companyName, Date sendDate, SalaryImportData salaryImportData, String salaryStr) {
        String title = buildTitle(ICON_URL, salaryStr, companyName, sendDate);
        String body = buildBody(companyName, sendDate, salaryStr, salaryImportData);
        String tail = buildTail(companyName, YUEYONG_URL);

        return title + body + tail;
    }

    private static String buildBody(String companyName, Date sendDate, String salaryStr, SalaryImportData salaryImportData) {
        String headFormat = "   <div class=\"table\" style=\"position: relative; width:580px;border: 10px solid  #F6F6FC;border-radius: 8px;margin-top:12px;\"> \n" +
                "    <div style=\"display: flex ;justify-content: space-between;    margin-left: 20px;margin-top:20px;margin-right: 20px;\"> \n" +
                "     <div style=\"\">\n" +
                "       %s\n" +
                "     </div> \n" +
                "     <div style=\"color: #777777;\">\n" +
                "       %s \n" +
                "     </div> \n" +
                "    </div> \n" +
                "    <div style=\"font-size: 13px;color: #FFFFFF;line-height: 18px;height: 28px; display: flex ;text-align: center;align-items: center;justify-content: center; background: #6633FF;  margin-left: 20px;margin-top:20px;margin-right: 20px;margin-bottom:18px;\">\n" +
                "      %s \n" +
                "    </div> \n ";
        String salaryInformation = "工资信息";

        DateFormat bf = new SimpleDateFormat("yyyy-MM");
        String format = bf.format(sendDate);

        String head = String.format(headFormat, companyName, format, salaryInformation);


        String table = buildSalaryTable(salaryImportData);

        String tailFormat = "\n</div> \n" +
                "    <div style=\"display: flex;justify-content: flex-end;align-items: center;margin-top: 18px;\"> \n" +
                "     <div style=\"font-size: 16px;font-weight: 500;color: #333333;line-height: 22px;\">\n" +
                "       实收工资： \n" +
                "     </div> \n" +
                "     <div style=\"font-size: 24px;font-weight: 500;color: #333333;line-height: 33px;margin-right: 20px;;\">\n" +
                "       %s \n" +
                "     </div> \n" +
                "    </div> \n" +
                "   </div>\n";
        String tail = String.format(tailFormat, salaryStr);
        return head + table + tail;

    }

    private static String buildSalaryTable(SalaryImportData salaryImportData) {

        String head = "    <div style=\"border: 1px solid #DADADA; width: calc(100% - 40px); box-sizing: border-box;font-size: 13px; margin-left: 20px;margin-right: 20px;\"> ";


        List<ItemData> itemDataList = salaryImportData.getSalaryData();

        StringBuilder content = new StringBuilder();

        for (ItemData itemData : itemDataList) {
            String moduleFormat = "\n<div style=\" font-size: 13px;height: 28px; display: flex ;  \"> \n" +
                    "      <div style=\"width: 50%%;height: 28px; font-size: 13px;font-weight: 400;color: #929292;display: flex;align-items: center;justify-content: center; text-align: center;\">\n" +
                    "        %s \n" +
                    "      </div> \n" +
                    "      <div style=\"width:1px; height: 28px; background:  #DADADA;\"> \n" +
                    "      </div> \n" +
                    "      <div style=\"width: 50%%;height: 28px; font-size: 13px;font-weight: 400;color: #333333;display: flex;align-items: center;justify-content: center;\">\n" +
                    "        %s \n" +
                    "      </div> \n" +
                    "     </div>\n";
            String module = String.format(moduleFormat, itemData.getItemName(), itemData.getItemValue());
            content.append(module);
            content.append("     <div style=\" height: 1px;background:  #DADADA;\"></div> \n");
        }
        return head + content;

    }

    private static String buildTitle(String imageUrl, String salaryStr, String companyName, Date sendDate) {
        final String titleDivFormat = "   <div class=\"title\">\n" +
                "     您好！\n" +
                "   </div> \n" +
                "   <div class=\"title\" style=\"margin-top:16px;\">\n" +
                "     您在%s%s实收工资\n" +
                "    <strong>%s</strong>元，具体明细如下：\n" +
                "   </div> ";

        DateFormat bf = new SimpleDateFormat("yyyy年MM月");
        String dateStr = bf.format(sendDate);


        String title = String.format(titleDivFormat, companyName, dateStr, salaryStr);

        final String imageFormat = "   <img style=\"width: 615px; margin-left:0px; margin-top: 14px\" src=\"%s\" alt=\"\"> ";
        String imageStr = String.format(imageFormat, imageUrl);
        return title + imageStr;
    }

    private static String buildTail(String companyName, String linkUrl) {
        String tailDivFormat = "<div style=\"margin-top:30px;font-size: 16px;font-weight: 400;color: #060606;line-height: 22px;\">\n" +
                "     %s \n" +
                "   </div> \n" +
                "   <div style=\"margin-top:10px;\"> \n" +
                "    <span style=\"height: 20px;font-size: 14px;font-weight: 400;color: #858585;line-height: 20px;\">\n" +
                "      %s \n" +
                "    </span> \n" +
                "    <a style=\"text-decoration: underline;height: 20px;font-size: 14px;font-weight: 500;color: #6633FF;line-height: 20px;\" href=\"%s\" target=\"_blank\">%s</a> \n" +
                "    <span style=\"height: 20px;font-size: 14px;font-weight: 400;color: #858585;line-height: 20px;\">\n" +
                "      %s \n" +
                "    </span> \n" +
                "   </div> \n" +
                "  </div>";

        String linkFormat = "此工资条仅供员工本人浏览，如对数据有疑问，请及时与%s联系！ ";
        String link = String.format(linkFormat, companyName);

        String manageFormat = "提示：本邮件由%s，使用%s的";
        String manage = String.format(manageFormat, companyName, platform);


        String outOfDuty = "\n平台服务创建并发送，本平台不对邮件内容负责。本邮件为系统发送，请勿直接回复。 \n";

        String tailDiv = String.format(tailDivFormat, link, manage, linkUrl, slaryPlatform, outOfDuty);

        return tailDiv;
    }
}
